package com.crm.jpaandthymeleaf.web.interceptor;

import com.crm.jpaandthymeleaf.utils.SysConstants;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author 周敬
 * @version 1.0
 * @packageName com.crm.jpaandthymeleaf.web.interceptor
 * @fileName AuthorizationInterceptor
 * @createTime 2021/12/17-16:37-星期五
 * @lastModify 2021/12/17-16:37-星期五
 */
public class AuthorizationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断用户是否登录
        if(request.getSession().getAttribute(SysConstants.SESSION_SYS_USER)==null){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print("<script>alert('请先进行登录，在进行后续操作!');location.href='"+request.getContextPath()+"/login'</script>");
            return false;
        }else{
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
